<template>
  <div id="socialSecurityRuleEdit" class="editCard">
    <el-form class="ruleForm grid-col-2" inline ref="ruleForm" label-width="165px" :model="ruleForm" :rules="rules">
      <el-form-item label="社保公积金规则名称：" prop="ruleName">
        <el-input v-model="ruleForm.ruleName" />
      </el-form-item>
      <el-form-item label="参保城市：" prop="insuredCityId">
        <CitySelect :data.sync="ruleForm.insuredCityId" placeholder="参保城市" @change="(data) => ruleForm.insuredCity = data.insuredCity" />
      </el-form-item>
      <el-form-item label="备注：" class="col-start-1 col-end-3" prop="remarks">
        <el-input v-model="ruleForm.remarks" />
      </el-form-item>
    </el-form>
    <el-card class="details">
      <template slot="header">
        <p>参保记录</p>
      </template>
      <el-card>
        <template slot="header">
          <p class="detailsTitle">社保明细</p>
        </template>
        <EditableTable ref="editTable" :tableData.sync="ruleForm.ssRuleItemList" :type="1" />
      </el-card>
      <el-card>
        <template slot="header">
          <p class="detailsTitle">公积金明细</p>
        </template>
        <EditableTable :tableData.sync="ruleForm.afRuleItemList" :type="2" />
      </el-card>
      <div class="totalStatistics">
        <span>个人承担合计：<span class="redColorFont">{{total.personalTotal}}</span></span>
        <span>公司承担合计：<span class="redColorFont">{{total.companyTotal}}</span></span>
        <span>全部合计：<span class="redColorFont">{{total.allTotal }}</span></span>
      </div>
    </el-card>
    <div class="footer">
      <el-button @click="goBack">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确认</el-button>
    </div>
  </div>
</template>
<script>
import { math } from '@/util/math.js';
import EditableTable from './components/EditableTable.vue';
import CitySelect from './components/CitySelect.vue';
export default {
  name: 'socialSecurityRuleEdit',
  components: {
    EditableTable,
    CitySelect
  },
  data() {
    return {
      ruleForm: {
        ruleName: '',
        insuredCity: '',
        insuredCityId: 0,
        remarks: '',
        ssRuleItemList: [
          { projectName: '养老', baseNumber: 0.00, personalRatio: 0, companyRatio: 0, personalAmount: 0, companyAmount: 0, totalAmount: 0, ruleType: 1 },
          { projectName: '失业', baseNumber: 0.00, personalRatio: 0, companyRatio: 0, personalAmount: 0, companyAmount: 0, totalAmount: 0, ruleType: 1 },
          { projectName: '医疗', baseNumber: 0.00, personalRatio: 0, companyRatio: 0, personalAmount: 0, companyAmount: 0, totalAmount: 0, ruleType: 1 },
          { projectName: '工伤', baseNumber: 0.00, personalRatio: 0, companyRatio: 0, personalAmount: 0, companyAmount: 0, totalAmount: 0, ruleType: 1 },
        ],
        afRuleItemList: [
          { projectName: '公积金', baseNumber: 0.00, personalRatio: 0, companyRatio: 0, personalAmount: 0, companyAmount: 0, totalAmount: 0, ruleType: 2 },
        ],
      },
      rules: { //表单校验规则
        ruleName: [
          { required: true, message: '请输入社保公积金规则名称', trigger: 'blur' },
        ],
        // insuredCityId: [
        //   { required: true, message: '请选择参保城市', trigger: 'blur' },
        // ]
      },
    };
  },
  computed: {
    total() {
      let personalTotal = 0.00, companyTotal = 0.00, allTotal = 0.00;

      this.ruleForm.ssRuleItemList.map(e => {
        personalTotal = math.add(personalTotal, e.personalAmount == '' ? 0 : e.personalAmount);
        companyTotal = math.add(companyTotal, e.companyAmount == '' ? 0 : e.companyAmount);
      });
      this.ruleForm.afRuleItemList.map(e => {
        personalTotal = math.add(personalTotal, e.personalAmount == '' ? 0 : e.personalAmount);
        companyTotal = math.add(companyTotal, e.companyAmount == '' ? 0 : e.companyAmount);
      });
      personalTotal = personalTotal.toFixed(2);
      companyTotal = companyTotal.toFixed(2);
      allTotal = math.add(personalTotal, companyTotal).toFixed(2);
      return {
        allTotal,
        personalTotal,
        companyTotal
      };
    },

  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },

    /**
     * @description 进入页面后，对表格数据进行初始化，选规则用规则数据，没选初始值
     */
    initTableData() {
      // 调用editTable提供的方法，将数据转化为显示类型
      this.ruleForm = this.$refs.editTable.formatTableData(this.ruleForm, 2);

    },
    searchRuleItem(ruleId, operateType) {
      this.$api.socialSecurity
        .GetSsafRuleDetail({ ruleId, operateType })
        .then(res => {
          if (res.data.status == 200) {
            this.ruleForm = res.data.data;
          }

          this.initTableData();
        });
    },
    saveRule(data) {
      this.$api.socialSecurity
        .AddSsafRule(data)
        .then(res => {
          if (res.data.status == 200) {
            this.$message.success(res.data.message);
            this.successSubmit();
          } else {
            this.$message.warning(res.data.message);
          }

        })
        .catch(err => {
          console.log(err);
        });
    },
    editRule(data) {
      this.$api.socialSecurity
        .EditSsafRule(data)
        .then(res => {
          if (res.data.status == 200) {
            this.$message.success(res.data.message);
            this.successSubmit();
          } else {
            this.$message.warning(res.data.message);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    /**
     * @description 新建，修改接口成功后，返回列表页并关闭当前页
     */
    successSubmit() {
      this.$store.commit('DEL_TAG', {
        value: this.$route.path,
        label: this.$route.meta.title
      });
      this.$router.go(-1);
    },
    handleSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 提交新增表单之前将明细表中各项数据从字符创转为数字
          let data = JSON.parse(JSON.stringify(this.ruleForm));
          data = this.$refs.editTable.formatTableData(data, 1);
          if (this.$route.query.activeId == -1 || this.$route.query.operateType == 2) { //新增和复制时，调用保存方法
            this.saveRule(data);
          } else { // 编辑时调用编辑方法
            this.editRule(data);
          }
        } else {
          return false;
        }
      });


    },

  },
  activated() {
    if (this.$route.query.activeId == -1) {
      this.initTableData();
    } else {
      this.searchRuleItem(this.$route.query.activeId, this.$route.query.operateType);
    }
    // 修改当前页面tag标签名称
    this.$store.commit('DEL_TAG', { value: this.$route.path });
    this.$store.commit('ADD_TAG', {
      value: this.$route.path,
      close: true,
      label: `${this.$route.query.activeId == -1 ? '新增' : '编辑'}规则`
    });

  }
};
</script>
<style lang="less" scoped>
@import url("./less/editCard.less");
#socialSecurityRuleEdit {
  padding: 20px;
  .ruleForm {
    height: 120px;
    width: 800px;
    :deep(.el-form-item) {
      // height: 40px;
      .el-form-item__content {
        width: calc(100% - 165px);
      }
    }
  }
  .footer {
    text-align: center;
  }
}
</style>